package models

import (
	"github.com/astaxie/beego/orm"
	"time"
)

// 场景-资源中间表
type Element struct {
	Id         int64     `orm:"pk;auto"`   // 项目ID
	Title      string    `orm:"size(255)"` //
	PinYin     string    `orm:"size(255)"` //拼音
	ParentId   int64     `orm:"size(11)"`  //场景id
	Status     int64     `orm:"size(1)"`   //场景id
	CreateAt   time.Time `orm:"auto_now_add;type(datetime)"form:"-"`
	CreateBy   int64     `orm:"size(11)"` //用户名称
	UpdateAt   time.Time `orm:"auto_now;type(datetime)"`
	UpdateName string    `orm:"size(20)"` //
	CreateName string    `orm:"size(20)"` //更新者姓名
	UpdateBy   int64     `orm:"size(11)"` //更新者姓名
}

// 获取模型表名
func (m *Element) TableName() string {
	return "element"
}

// 获取全部用户
func (m *Element) GetAllElments() []*Element {
	list := make([]*Element, 0)
	_, _ = m.Query().All(&list)
	return list
}

// 查询方法
func (m *Element) Query() orm.QuerySeter {
	return orm.NewOrm().QueryTable(m)
}

// 添加用户
func (m *Element) Insert() error {
	_, err := orm.NewOrm().Insert(m)
	return err
}

// 删除用户
func (m *Element) Delete() error {
	_, err := orm.NewOrm().Delete(m)
	return err
}

// 修改用户信息
func (m *Element) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(m, fields...)
	return err
}
func (m *Element) Read(fields ...string) (int64, error) {
	if err := orm.NewOrm().Read(m, fields...); err != nil {
		return 0, err
	}
	return m.Id, nil
}

// 通过ID查询单个用户信息
func (m *Element) GetElementById(uid int64) (*Element, error) {
	err := m.Query().Filter("id", uid).One(m)
	return m, err
}

// 通过ID查询单个用户信息
// 通过父节点获取project
func (m *Element) GetEleParentListsByParentId(uid int64) []map[string]interface{} {
	list := make([]*Element, 0)
	_, _ = m.Query().Filter("parent_id", uid).All(&list)
	resTree := make([]map[string]interface{}, 0)
	for _, citem := range list {
		cres := ElementJson(citem)
		resTree = append(resTree, cres)
	}
	return resTree
}
func (m *Element) GetEleParentListsByParentId4(uid int64) []map[string]interface{} {
	list := make([]*Element, 0)
	_, _ = m.Query().Filter("parent_id", uid).All(&list)
	resTree := make([]map[string]interface{}, 0)
	for _, citem := range list {
		cres := ElementJson(citem)
		cres["level"] = 3
		resTree = append(resTree, cres)
	}
	return resTree
}

func (m *Element) GetEleListsByRandomId(uid int64) []map[string]interface{} {
	list := make([]*Element, 0)
	_, _ = m.Query().Filter("parent_id__gt", uid).All(&list)
	resTree := make([]map[string]interface{}, 0)
	for _, citem := range list {
		cres := ElementJson(citem)
		resTree = append(resTree, cres)
	}
	return resTree
}
